"use strict";

const titbit = require("titbit");
const { cookie, session } = require("titbit-toolkit");

const app = new titbit({
    debug: true,
});

// session是基于cookie存在的，session和cookie往往会成对出现
// 前端cookie后端session存储

app.use(
    async (c, next) => {
        if (c.query.key !== "12345") {
            return c.status(403).send("deny");
        }
        await next();
    },
    { group: "session" }
);

app.use(async (c, next) => {
    console.log("time started");
    let startTime = Date.now();
    await next();
    let endTime = Date.now();
    console.log(endTime - startTime, "ms");
});

// use执行符合逻辑
app.use(new cookie()).use(new session());

app.use(
    async (c, next) => {
        console.log("home started");
        await next();
        console.log("home end");
    },
    // 指名这个中间段只针对于这样的group执行
    { group: "home", method: ["GET"] }
);

app.get(
    "/",
    async (c) => {
        c.send("ok");
    },
    // 做标记
    { name: "主页", group: "home" }
);

app.get(
    "/sess/:x/:y",
    async (c) => {
        c.setSession("x", c.param.x);
        c.setSession("y", c.param.y);

        c.send(c.getSession());
    },
    // 添加的路由
    { group: "session" }
);

app.run(2346);
